`timescale 1ns / 1ps

// mod N binary counter
module zq_counter
#(
    parameter N = 16
)
(
    input   clk,
    input   rst,
    input   clken,
    
    output  last,
    output  [$clog2(N)-1: 0] out
);

localparam WIDTH = $clog2(N);
localparam [WIDTH-1: 0] ZEROS = {WIDTH{1'b0}};
localparam [WIDTH-1: 0] CNT_MAX = N - 1;

reg [WIDTH-1: 0] cnt;

assign out = cnt;
assign last = (cnt == CNT_MAX);

always @ (posedge clk)
begin
    if (rst) begin
        cnt <= ZEROS;
    end
    else if (clken) begin
        if (~last)
            cnt <= cnt + 1'b1;
        else
            cnt <= ZEROS;
    end
end

endmodule
